﻿using CloudMusic.Helper;
using CloudMusic.Model;
using DMSkin.Core.Common;
using DMSkin.Core.MVVM;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;

namespace CloudMusic.ViewModel
{
    /// <summary>
    /// 本地音乐viewmodel
    /// </summary>
    public class PageLocalMusicViewModel : MusicViewModelBase
    {
        public PageLocalMusicViewModel()
        {
            Read();
            if (PlayListHelper.MainMusicList.Count>0)
            {
                SelectedMusic = PlayListHelper.MainMusicList[0];
            }
        }
        /// <summary>
        /// 读取配置
        /// </summary>
        public void Read()
        {
            if (File.Exists("LocalMusic.json"))
            {
                //尝试从 配置文件中读取 上次 增加的 播放列表
                string json = File.ReadAllText("LocalMusic.json");
                if (!string.IsNullOrEmpty(json))
                {
                    List<MusicModel> list = JsonConvert.DeserializeObject<List<MusicModel>>(json);
                    foreach (var item in list)
                    {
                        MusicList.Add(item);
                        //MainMusicList.Add(item);
                    }
                    //显示歌曲列表
                    ShowMusicList();                
                }
            }
        }

        /// <summary>
        /// 写入配置
        /// </summary>
        public void Save()
        {
            string json = JsonConvert.SerializeObject(MusicList);
            File.WriteAllText("LocalMusic.json", json);
        }

     
        /// <summary>
        /// 新增文件夹
        /// </summary>
        public ICommand AddFileCommand
        {
            get
            {
                return new DelegateCommand(obj =>
                {
                    System.Windows.Forms.OpenFileDialog openFile = new System.Windows.Forms.OpenFileDialog();
                    openFile.CheckFileExists = true;//检查文件是否存在
                    openFile.CheckPathExists = true;//检查路径是否存在
                    openFile.Multiselect = true;//是否允许多选，false表示单选
                    openFile.InitialDirectory = "C:\\";//设置打开时的默认路径，我这里设置为C盘根目录
                    string filter = "mp3,wav,aac,flac";
                    filter = filter.TrimEnd(',');
                    if (filter.Equals(""))
                    {
                        filter = "*";
                    }
                    filter = filter.Replace(",", ";*.");
                    filter = "*." + filter;
                    openFile.Filter = "音频文件 (" + filter + ")|" + filter + "|所有文件 (*.*)|*.*";//这里设置的是文件过滤器，比如选了txt文件，那别的文件就看不到了

                    int index = MusicList.Count > 0 ? MusicList.Count+1:1;
                    if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)//打开文件选择器，并按下选择按钮
                    {
                        List<MusicModel> TempList = new List<MusicModel>();
                        String[] names = openFile.FileNames;
                        if (names.Length>0)
                        {
                            for (int i = 0; i < names.Length; i++)
                            {
                                string[] exts = { ".mp3", ".flac", ".aac", ".wav" };//仅添加这几种格式

                                FileInfo file = new FileInfo(names[i]);
                                var tfile = TagLib.File.Create(file.FullName);
                                MP3Info m = new MP3Info();
                                m.GetMP3Info(file.DirectoryName, file.Name);

                                if (exts.Contains(file.Extension))
                                {
                                    TempList.Add(new MusicModel()
                                    {
                                        Name = m.trackName,
                                        Size = file.Length,
                                        Index = index > 9 ? index.ToString() : "0" + index.ToString(),
                                        Url = file.FullName,
                                        Album = m.Album,
                                        Artist = string.Join("/", tfile.Tag.Performers),
                                        TimeStr = m.time.Substring(3),
                                        Id = i+1,
                                        Type = 0
                                    });
                                    index++;
                                }
                            }
                            if (TempList.Count > 0)
                            {
                                Execute.OnUIThread(() =>
                                {
                                    foreach (var item in TempList)
                                    {
                                        if (MusicList.Where(p => p.Name == item.Name).Count() == 0)
                                        {
                                            MusicList.Add(item);
                                        }
                                    }
                                    //显示歌曲列表
                                    ShowMusicList();
                                    //保存找到的歌曲
                                    Save();
                                });
                            }
                        }
                       
                    }
                });
            }
        }
        //private void FindMusic(List<string> filelist)
        //{
        //    int index = 1;
        //    List<Music> TempList = new List<Music>();
        //    foreach (var item in filelist)
        //    {
        //        FileInfo file = new FileInfo(item);
        //        var tfile = TagLib.File.Create(file.FullName);
        //        MP3Info m = new MP3Info();
        //        m.GetMP3Info(file.DirectoryName, file.Name);

        //        if (file.Extension.Contains(".mp3"))
        //        {
        //            TempList.Add(new Music()
        //            {
        //                Title = m.trackName,
        //                Size = file.Length,
        //                Index = index > 9 ? index.ToString() : "0"+index.ToString(),
        //                Url = file.FullName,
        //                Album = m.Album,
        //                Artist = m.Artist,
        //                TimeStr = m.time.Substring(3),
        //                Id = index,
        //                Type=0
        //            });
        //            index++;
        //        }
        //    }
        //    if (TempList.Count > 0)
        //    {
        //        Execute.OnUIThread(() =>
        //        {
        //            foreach (var item in TempList)
        //            {
        //                if (MusicList.Where(p => p.Title == item.Title).Count() == 0)
        //                {
        //                    MusicList.Add(item);
        //                }
        //            }
        //            //显示歌曲列表
        //            ShowMusicList();
        //            //保存找到的歌曲
        //            Save();
        //        });
        //    }
        //}
    }
}
